package net.babypai.adapter;

import java.util.List;

import net.babypai.R;
import net.babypai.model.ChatMessage;
import net.babypai.model.ChatMessageList;
import net.babypai.utils.TimeUtil;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ChattingAdapter extends BaseAdapter {
	protected static final String TAG = "ChattingAdapter";
	private Context context;
	private List<ChatMessage> info = null;

	public ChattingAdapter(Context context, ChatMessageList chattingMainInfoList) {
		super();
		this.context = context;
		this.info = chattingMainInfoList.getInfo();

	}

	@Override
	public int getCount() {
		return info.size();
	}

	@Override
	public Object getItem(int position) {
		return info.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		ChatMessage message = (ChatMessage) getItem(position);
		if (convertView == null
				|| (holder = (ViewHolder) convertView.getTag()).flag != message
						.getDirection()) {

			holder = new ViewHolder();
			if (message.getDirection() == ChatMessage.MESSAGE_FROM) {
				holder.flag = ChatMessage.MESSAGE_FROM;

				convertView = LayoutInflater.from(context).inflate(
						R.layout.chatting_item_from, null);
			} else {
				holder.flag = ChatMessage.MESSAGE_TO;
				convertView = LayoutInflater.from(context).inflate(
						R.layout.chatting_item_to, null);
			}

			holder.text = (TextView) convertView
					.findViewById(R.id.chatting_content_itv);
			holder.chatting_time_tv = (TextView) convertView
					.findViewById(R.id.chatting_time_tv);
			convertView.setTag(holder);
		}
		holder.text.setText(message.getContent());
		holder.chatting_time_tv.setText(TimeUtil.getTimeStr(message
				.getAddtime()));
		return convertView;
	}

	static class ViewHolder {
		TextView text;
		TextView chatting_time_tv;
		int flag;
	}

}
